import "./index.less";
import {useCallback, useEffect, useMemo, useState} from "react";
import {formateDate} from "../../utils/dateUtils.ts";
import memoryUtils from "../../utils/memoryUtils.ts";
import {useLocation, useNavigate} from "react-router-dom";
import menuList from "../../config/menuConfig";
import {reqWeather} from "../../apis/index.ts";
import {message, Modal} from "antd";
import storageUtils from "../../utils/storageUtils.ts";
import {ExclamationCircleFilled} from "@ant-design/icons";
/*头部组件
 */

const Header = () =>{
    // 获取当前时间
    const [date, setDate] = useState(formateDate(Date.now()))
    // 获取用户名
    const username = memoryUtils.user.username
    // 获取当前路由对应的标题名
    const current_path = useLocation()
    // 设置标题
    const [title,setTitle] = useState('')
    // 获取当前路由对应的标题名
    const getTitle = useCallback(() => {
        // console.log('当前路径', current_path.pathname)
        let temp_path = ''
        menuList.forEach(item =>{
            if(item.key === current_path.pathname){
                // 匹配到一级路径值 暂存入 temp_path
                temp_path = item.label
            }else if(item.children){
                // 选中到子路由
                const subItem = item.children.find(subItem => subItem.key === current_path.pathname)
                if(subItem){
                    temp_path = subItem.label
                }
            }
        })

        return temp_path

    },[current_path.pathname])
    // 开启定时器 获取最新时间 直接渲染 date 会导致时间栏 闪烁
    // useEffect 中的定时器过于频繁地更新状态。每秒调用一次 formateDate 函数并更新 date 状态会导致组件不断重新渲染，从而导致闪烁。
    // 使用 useMemo 缓存格式化后的日期
    // 仅在必要时更新状态：可以使用 useMemo 钩子来缓存 date 的格式化值，只有当 date 本身发生变化时才更新状态：
    const formattedDate = useMemo(() => formateDate(date), [date]);
    // 获取天气
    const [weather, setWeather] = useState('晴')
    const getWeather = async() =>{
        // 调用接口获取天气
       try{
           const res = await reqWeather()
           const weather = res[0].weather
           setWeather(weather)
       }catch(error){
           message.error('获取天气失败')
       }
    }
    useEffect(() => {
        let temp_path = getTitle()
        // console.log('temp_path', temp_path)
        setTitle(temp_path)
        // 获取天气
        getWeather()
        // 设置定时器 不断获取最新时间
        let timer = setInterval(()=>{
            setDate(date =>  formateDate(Date.now()))
        },1000)
        // 返回值是 组件销毁前的生命周期
        return () => {
            // 组件销毁前，销毁定时器
            clearInterval(timer)
        }
    }, [getTitle]);
      // 退出登录
    const navigate = useNavigate()
    // 引入Modal
    const {confirm} = Modal
    const logout = () => {
        confirm({
            // title: 'Do you Want to delete these items?',
            icon: <ExclamationCircleFilled />,
            content: '确定退出登陆吗?',
            onOk() {
                console.log('OK');
                // 删除保存的user数据
                memoryUtils.user = {}
                storageUtils.removeUser()
                // 跳转至login页面
                navigate('/login')
            },
        });
    }
      return (
          <div className="header">
            <div className="header-top">
              <span>欢迎, {username}</span>
                <a href="#" onClick={logout}>退出</a>
            </div>
            <div className="header-bottom">
              <div className="header-bottom-left">{title}</div>
              <div className="header-bottom-right">
                <span>{formattedDate}</span>
                <img src="" alt="weather"/>
                <span>{weather}</span>
              </div>
            </div>
          </div>
      )
}
export default Header;